package ACM_Brush;

import java.util.HashMap;
import java.util.Map;

public class Solution230 {
    public static void main(String[] args) {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(1);
        root.left.right = new TreeNode(2);
        root.right = new TreeNode(4);
        System.out.println();
        System.out.println(new solution_230().kthSmallest(root, 1));
    }
}

class solution_230 {
    public Map<TreeNode, int[]> map = new HashMap<>();

    public int kthSmallest(TreeNode root, int k) {
        countLeftAndRight(root);
        if (k == map.get(root)[0] + 1)
            return root.val;
        else if (k <= map.get(root)[0])
            return kthSmallest(root.left, k);
        else
            return kthSmallest(root.right, k - (map.get(root)[0] + 1));
    }

    private int countLeftAndRight(TreeNode root) {
        if (root == null)
            return 0;
        int countLeft = countLeftAndRight(root.left);
        int countRight = countLeftAndRight(root.right);
        map.put(root, new int[] { countLeft, countRight });
        return countLeft + countRight + 1;
    }
}